package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在链接服务端...");
            socket=new Socket("localhost",8088);// 192.168.0.113
//            socket=new Socket("192.168.0.112",8088);///
            System.out.println("链接服务端成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            //启动读取服务端的线程
            SreverHandler handle = new SreverHandler();
            Thread t = new Thread(handle);
            t.setDaemon(true);//其他线程结束，这个也跟着结束；
            t.start();

            //写入服务端
            OutputStream os = socket.getOutputStream();//作用---输出byte
            OutputStreamWriter osw = new OutputStreamWriter(os);//作用char转换成byte；
            BufferedWriter bw = new BufferedWriter(osw);//作用---缓冲
            PrintWriter pw = new PrintWriter(bw,true);//作用---str转换char[]成且默认是utf8输出，和str.getBytes(StandardCharsets.UTF_8)

            //手动输入

            System.out.println("请输入传输的内容！");
            Scanner scan = new Scanner(System.in);
            String str ;
            while(!"exit".equalsIgnoreCase(str = scan.nextLine())){//scan.nextLine()有停顿作用
                if(!"".equalsIgnoreCase(str)){//不能写入空字符
                    pw.println(str);
                }

            }
        } catch (IOException e) {

            e.printStackTrace();
        }finally {
            try {
                //四次挥手操作；
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();

    }

    private class SreverHandler implements Runnable{

        public void run(){
            try {
                //从服务端写入
                InputStream is = socket.getInputStream();//低级流----8位bit 1个byte
                InputStreamReader isr = new InputStreamReader(is);//转换流---byte转成char 或char[]
                BufferedReader br = new BufferedReader(isr);//缓冲流---堆积char,和上面类似，但是带flush；
                //默认是8K字节；
                String message;
                while ((message = br.readLine())!=null){
                    System.out.println("客户端说："+message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
